package com.coderside.fragment.thread.ABC;

import java.util.concurrent.CountDownLatch;

/**
 * 多线程循环打印ABCABC
 * 
 * @author
 * 
 */
public class ThreadPrintABC_3 {
	private static int count = 100;
	final static CountDownLatch c = new CountDownLatch(3 * count);

	public static void main(String[] args) {
		long a = System.currentTimeMillis();
		new Thread(new TestRun("A", c)).start();
		new Thread(new TestRun("B", c)).start();
		new Thread(new TestRun("C", c)).start();

		try {
			c.await();
			long b = System.currentTimeMillis();
			System.out.println(b - a);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}

class TestRun implements Runnable {
	private String name;
	private static String flag = "A";
	private int count = 100;
	private CountDownLatch c;

	TestRun(String name, CountDownLatch c) {
		this.name = name;
		this.c = c;
	}

	public void run() {
		while (count > 0) {
			synchronized (flag) {
				if (flag.equals(name)) {
					System.out.print(name);
					count--;
					if (name.equals("A"))
						flag = "B";
					if (name.equals("B"))
						flag = "C";
					if (name.equals("C"))
						flag = "A";
					c.countDown();
				}
			}
		}
	}

}